<template>
  <div>
    <!-- 储值卡 -->
    <div class="br-12 c-white balance_box">
      <div class="pt-26 pb-32 pl-28 pr-40 d-ce-bet-flex">
        <div class="">
          <div class="fs-30 lh-1-5 fw-600">储值卡</div>
          <div class="d-flex align-items-center mt-36">
            <!-- 卡信息列表 -->
            <div v-for="(item, index) in cardList" :key="index" class="mr-114">
              <div class="fs-16 lh-22">{{ item.title }}</div>
              <div class="fs-32 lh-1-5 fw-700 mt-7">
                <span>{{ item.symbol }}{{ item.balance }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="d-flex">
          <button
            class="button-004 primary button-004&#45;&#45;large chongzhi_btn"
          >
            充值
          </button>
          <button
            class="button-004 ml-28 primary button-004&#45;&#45;large chongzhi_btn"
          >
            申请总卡数
          </button>
        </div>
      </div>
    </div>
    <el-card class="box-card">
      <el-row>
        <div class="horoscope-list">
          <span class="fs-18">星座卡列表</span>
          <i class="el-icon-refresh-right"></i>
        </div>
        <el-divider />
        <el-tabs v-model="tabIndex" @tab-click="handleChangeHeader">
          <el-tab-pane
            v-for="(item, index) in headerList"
            :key="index"
            :label="item.name"
            :name="item.name"
          >
            <span slot="label">
              {{ `${item.name}(${item.num + ''})` }}
            </span>
          </el-tab-pane>
        </el-tabs>
        <el-divider />
        <el-form
          ref="form"
          :inline="true"
          :model="queryForm"
          @submit.native.prevent
        >
          <el-form-item prop="last_no">
            <el-input
              v-model="queryForm.last_no"
              placeholder="请输入卡后四位"
            />
          </el-form-item>
          <el-form-item prop="cardbin">
            <el-select v-model="queryForm.cardbin" placeholder="所有卡段">
              <el-option
                v-for="item in cardBinList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="label">
            <el-select
              v-model="queryForm.label"
              clearable
              placeholder="请选择标签"
            >
              <el-option
                v-for="item in labelList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="createTime">
            <el-date-picker
              v-model="queryForm.createTime"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              type="daterange"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              native-type="submit"
              type="purple"
              @click="handleQuery"
            >
              查询
            </el-button>
            <el-button
              icon="el-icon-search"
              native-type="submit"
              type="default"
              @click="resetList"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
        <div style="display: flex; justify-content: space-between">
          <div>
            <el-button
              native-type="submit"
              plain
              type="purple"
              @click="toPage('/prepaidCard-add')"
            >
              <vab-icon icon="add-circle-line" />
              新增星座卡
            </el-button>
            <el-button
              icon="el-icon-download"
              native-type="submit"
              plain
              style="margin-right: 8px"
              type="primary"
            >
              导出卡数据
            </el-button>
            <el-dropdown
              popper-class="dropDown_style"
              trigger="click"
              @command="handleCommand"
            >
              <el-button>
                <i class="el-icon-folder-checked"></i>
                批量操作
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <!-- <el-dropdown-item command="topup">批量充值</el-dropdown-item> -->
                  <el-dropdown-item command="transfer">
                    批量划出
                  </el-dropdown-item>
                  <el-dropdown-item command="label">
                    批量修改卡标签
                  </el-dropdown-item>
                  <el-dropdown-item command="delete">批量销卡</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <el-popover popper-class="custom-table-checkbox" trigger="hover">
            <el-checkbox-group v-model="checkList">
              <vab-draggable v-bind="dragOptions" :list="columns">
                <div v-for="(item, index) in columns" :key="item + index">
                  <vab-icon icon="drag-drop-line" />
                  <el-checkbox
                    :disabled="item.disableCheck === true"
                    :label="item.label"
                  >
                    {{ item.label }}
                  </el-checkbox>
                </div>
              </vab-draggable>
            </el-checkbox-group>
            <template #reference>
              <el-button
                icon="el-icon-setting"
                plain
                style="margin: 0 0 10px 0 !important"
                type="primary"
              >
                配置
              </el-button>
            </template>
          </el-popover>
        </div>
        <el-table
          ref="tableSort"
          v-loading="listLoading"
          :border="border"
          :data="list"
          :height="height"
          :size="lineHeight"
          :stripe="stripe"
          @selection-change="setSelectRows"
        >
          <!-- <el-table-column align="center" type="selection" width="55" />
          <el-table-column
            align="center"
            label="序号"
            show-overflow-tooltip
            width="95"
          >
            <template #default="{ $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column> -->
          <el-table-column
            v-for="(item, index) in finallyColumns"
            :key="index"
            align="center"
            :label="item.label"
            :prop="item.prop"
            :sortable="item.sortable"
            :width="item.width"
          >
            <template #default="{ row }">
              <el-tag
                v-if="item.label === '卡片状态'"
                :type="
                  row.status == 1
                    ? 'success'
                    : row.status == 0
                    ? 'danger'
                    : 'info'
                "
              >
                {{ row.status_text }}
              </el-tag>
              <span v-else>{{ row[item.prop] }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="操作"
            show-overflow-tooltip
            width="220"
          >
            <template #default="{ row }">
              <el-button type="text" @click="handleTopup(row, '资金充值')">
                充值
              </el-button>
              <el-button type="text" @click="handleTopup(row, '资金划转')">
                划出
              </el-button>
              <el-button type="text" @click="handleDelete(row)">冻结</el-button>
              <el-button type="text" @click="handleDelete(row)">销卡</el-button>
              <el-button type="text" @click="goCardDetail(row)">详情</el-button>
            </template>
          </el-table-column>
          <template #empty>
            <el-image
              class="vab-data-empty"
              :src="require('@/assets/empty_images/data_empty.png')"
            />
          </template>
        </el-table>
        <el-pagination
          background
          :current-page="queryForm.page"
          :layout="layout"
          :page-size="queryForm.limit"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </el-row>
    </el-card>
    <!--充值弹框 -->
    <hsk-dialog
      :center="false"
      :close-on-click-modal="false"
      :confirm-loading="confirmLoading"
      custom-class="custom-dialog"
      :show-footer="false"
      :title="title"
      :visible.sync="dialogTopup"
      :width="dialogWidth"
    >
      <el-form ref="topupForm" :model="topupForm" :rules="topupRules">
        <div class="fs-14 lh-20 fw-600 c-333 red_dot mb-10 c-theme-black-1">
          划转类型
        </div>
        <el-form-item class="mb-0 mt-18 w-full">
          <el-radio-group
            v-model="topupForm.transferType"
            size="medium"
            @input="transferTypeChange"
          >
            <el-radio
              v-for="(item, index) in transferTypeList"
              :key="index"
              border
              :label="item.value"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="title === '资金充值'">
          <div class="fs-14 lh-20 fw-600 c-333 mb-10 c-theme-black-1 mt-24">
            充值到卡
          </div>
          <el-form-item class="mb-0 mt-18 w-full">
            <el-input
              v-model="topupForm.api_card_no"
              class="input_vaild"
              disabled
            />
          </el-form-item>
        </div>
        <div v-else>
          <div class="fs-14 lh-20 fw-600 c-333 mb-10 c-theme-black-1 mt-24">
            扣款卡片
          </div>
          <el-form-item class="mb-0 mt-18 w-full">
            <el-input
              v-model="topupForm.api_card_no"
              class="input_vaild"
              disabled
            />
          </el-form-item>
        </div>
        <div v-if="title === '资金充值'">
          <div
            class="fs-14 lh-20 fw-600 c-333 red_dot mb-10 c-theme-black-1 mt-24"
          >
            充值金额
          </div>
          <el-form-item class="mb-0 mt-18 w-full">
            <el-input
              v-model="topupForm.authLimitAmount"
              class="input-004 input-004--border input-004--normal"
              :clearable="false"
              placeholder="请输入充值金额"
              type="Number"
            >
              <template #append>USD</template>
            </el-input>
          </el-form-item>
        </div>
        <div v-else>
          <div
            class="fs-14 lh-20 fw-600 c-333 red_dot mb-10 c-theme-black-1 mt-24"
          >
            转出金额
          </div>
          <el-form-item class="mb-0 mt-18 w-full">
            <el-input
              v-model="topupForm.refundAmount"
              class="input-004 input-004--border input-004--normal"
              :clearable="false"
              placeholder="请输入转出金额"
              type="Number"
            >
              <template #append>USD</template>
            </el-input>
          </el-form-item>
        </div>
        <el-form-item v-if="title === '资金充值'" class="mb-0 mt-40 w-full">
          <div class="dfjc fs-14 lh-20 c-theme-black-1">
            <div>账户余额</div>
            <div>{{ topupForm.current_balance }} USD</div>
          </div>
          <div class="h-28" />
          <div class="dfjc fs-14 lh-20 c-theme-black-1">
            <div>入账金额</div>
            <div>2 USD</div>
          </div>
          <div class="h-28" />
          <div>
            <div class="dfjc fs-14 lh-20 c-theme-black-1">
              <div>账户转入手续费</div>
              <div>3USD</div>
            </div>
            <div class="h-12" style="display: none"></div>
          </div>
          <div class="h-24" />
          <div class="dfjc fs-14 lh-20 c-theme-black-1">
            <span>总费用</span>
            <div class="fs-18 lh-28 fw-600 c-theme-red">4 USD</div>
          </div>
        </el-form-item>
        <el-form-item v-else class="mb-0 mt-40 w-full">
          <div class="dfjc fs-14 lh-20 c-theme-black-1">
            <div>可用余额</div>
            <div>{{ topupForm.current_balance }} USD</div>
          </div>
        </el-form-item>
        <el-form-item>
          <div class="dialog-footer mt-32">
            <button class="button-004 button-004--secondary button-004--large">
              <span @click="dialogTopup = false">取消</span>
            </button>
            <button class="button-004 button-004--primary button-004--large">
              <span @click="confirmSubmit">立即充值</span>
            </button>
          </div>
        </el-form-item>
      </el-form>
    </hsk-dialog>
  </div>
</template>

<script>
  import { doDelete } from '@/api/table'
  import eduka from '@/assets/image/edukayue.png'
  import liangzika from '@/assets/image/lianzikayue.png'
  import chuzhika from '@/assets/image/chuzhikayue.png'
  import {
    getLabelList,
    getCardBinds,
    getCardListHeader,
    getCardList,
  } from '@/api/card'
  import VabDraggable from 'vuedraggable'
  import { mapGetters } from 'vuex'
  import { toThousands } from '@/utils'
  import { sendData } from '@/utils/websocket'

  export default {
    name: 'PrepaidCard',
    components: {
      VabDraggable,
    },
    data() {
      return {
        title: null,
        dialogWidth: '450px',
        confirmLoading: true,
        dialogTopup: false,
        topupForm: {},
        topupRules: {},
        transferTypeList: [
          {
            label: '充值',
            value: '31',
          },
          {
            label: '划出',
            value: '35',
          },
        ],
        cardList: null,
        border: true,
        height: this.$baseTableHeight(1),
        stripe: false,
        lineHeight: 'medium',
        checkList: [
          '卡号',
          '持卡人',
          '有效期',
          '安全码',
          '标签',
          '卡片状态',
          '累计消费($)',
          '可用余额($)',
          '操作',
        ],
        columns: [
          {
            label: '卡号',
            width: 'auto',
            prop: 'api_card_no',
          },
          {
            label: '持卡人',
            width: 'auto',
            prop: 'wholename_text',
          },
          {
            label: '有效期',
            width: '200',
            prop: 'api_card_expire',
          },
          {
            label: '安全码',
            width: 'auto',
            prop: 'api_card_cvv',
          },
          {
            label: '标签',
            width: 'auto',
            prop: 'label',
          },
          {
            label: '卡片状态',
            width: 'auto',
            prop: 'status_text',
          },
          {
            label: '累计消费($)',
            width: 'auto',
            prop: 'total_cost',
          },
          {
            label: '可用余额($)',
            width: 'auto',
            prop: 'current_balance',
          },
        ],
        list: [],
        listLoading: true,
        layout: '->,total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          page: 1,
          limit: 10,
          createTime: [],
          trade_id: '',
          last_no: '',
          type: '',
          status: '',
          label: '',
          wholename: '',
          card_id: '',
        },
        cardBinList: null,
        labelList: null,
        headerList: null,
        tabIndex: null,
        pickerOptions: {
          disabledDate(date) {
            return date.getTime() > Date.now()
          },
        },
      }
    },
    computed: {
      dragOptions() {
        return {
          animation: 600,
          group: 'description',
        }
      },
      finallyColumns() {
        return this.columns.filter((item) =>
          this.checkList.includes(item.label)
        )
      },
      ...mapGetters({
        infoDetail: 'user/infoDetail',
      }),
    },
    created() {
      this.cardList = [
        {
          title: '量子账户余额',
          balance: toThousands(this.infoDetail.money),
          img: liangzika,
          symbol: '$',
        },
        {
          title: '卡内总余额',
          balance: toThousands(this.infoDetail.card_total_money),
          img: chuzhika,
          symbol: '$',
        },
        {
          title: '剩余可用开卡数',
          balance: toThousands(this.infoDetail.card_remain),
          img: eduka,
        },
      ]
      this.getCardHeader()
      this.getCardBinList()
      this.getlabelList()
      // this.fetchData()
    },
    methods: {
      setSelectRows(val) {
        this.selectRows = val
      },
      toPage(item) {
        this.$router.push(item)
      },
      handleAdd() {
        this.$refs['edit'].showEdit()
      },
      handleEdit(row) {
        this.$refs['edit'].showEdit(row)
      },
      handleDelete(row) {
        if (row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await doDelete({ ids: row.id })
            this.$baseMessage(msg, 'success', 'vab-hey-message-success')
            await this.fetchData()
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => item.id).join()
            this.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids: ids })
              this.$baseMessage(msg, 'success', 'vab-hey-message-success')
              await this.fetchData()
            })
          } else {
            this.$baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      },
      handleSizeChange(val) {
        this.queryForm.limit = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.page = val
        this.fetchData()
      },
      handleQuery() {
        this.queryForm.page = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        this.queryForm = Object.assign(this.queryForm, {
          createtime: this.queryForm.createTime
            ? this.queryForm.createTime.join('~')
            : '',
        })
        const {
          data: { data, total },
        } = await getCardList(this.queryForm)
        this.list = data
        this.total = total
        this.listLoading = false
      },
      async getCardBinList() {
        let query = { type: 3 }
        const { data } = await getCardBinds(query)
        if (data) {
          this.cardBinList =
            data.map((item) => ({
              label: item,
              value: item,
            })) || []
        }
      },
      async getlabelList() {
        const {
          data: { data },
        } = await getLabelList()
        if (data) {
          this.labelList =
            data.map((item) => ({
              label: item.label,
              value: item.label,
            })) || []
        }
      },
      async getCardHeader() {
        const { data } = await getCardListHeader()
        if (data) {
          this.headerList = data || []
          this.tabIndex = data[0].name
          this.queryForm.status = data[0].type
          this.fetchData()
        }
      },
      handleChangeHeader(val) {
        this.queryForm.status = this.headerList[val.index - 0].type
        this.resetList()
      },
      resetList() {
        this.queryForm.page = 1
        this.$refs.form.resetFields()
        this.fetchData()
      },
      // 星座卡详情
      goCardDetail(row) {
        this.$router.push({
          name: 'prepaidCardDetail',
          query: { id: row.api_card_id },
        })
      },
      // 批量操作
      handleCommand(command) {
        if (command === 'label') {
          this.$router.push({
            name: 'handlePage',
            query: { command: command, title: '批量修改卡标签' },
          })
        } else if (command === 'delete') {
          this.$router.push({
            name: 'handlePage',
            query: { command: command, title: '批量删除卡' },
          })
        } else if (command === 'transfer') {
          this.$router.push({
            name: 'handlePage',
            query: { command: command, title: '批量划转' },
          })
        } else if (command === 'topup') {
          this.$router.push({
            name: 'handlePage',
            query: { command: command, title: '批量充值' },
          })
        }
      },
      // 充值弹框
      handleTopup(row, title) {
        console.log(row)
        this.dialogTopup = true
        if (title === '资金充值') {
          this.title = title
          this.topupForm.transferType = '31'
          this.topupForm.api_card_no = row.api_card_no
          this.topupForm.current_balance = row.current_balance
        } else if (title === '资金划转') {
          this.title = title
          this.topupForm.transferType = '35'
          this.topupForm.current_balance = row.current_balance
        }
      },
      // 切换划转类型
      transferTypeChange(val) {
        this.topupForm.transferType = val
      },
      // 确认充值
      confirmSubmit() {
        let loading
        const pack = {
          code: this.topupForm.transferType,
          data: {
            cardId: this.topupForm.api_card_id, //第三方卡ID
            authLimitAmount: this.topupForm.authLimitAmount, //卡片充值金额
          },
        }
        console.log(pack)
        // loading = this.$loading({
        //   lock: true,
        //   text: '充值中',
        //   spinner: 'el-icon-loading',
        //   background: 'rgba(0, 0, 0, 0.7)',
        // })
        // sendData(pack, () => {
        //   if (loading) {
        //     loading.close()
        //   }
        // })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .custom-table-container {
    :deep() {
      i {
        cursor: pointer;
      }
    }

    .stripe-panel,
    .border-panel {
      margin: 0 10px #{$base-margin/2} 10px !important;
    }
  }
  .balance_box {
    position: relative;
    margin-bottom: 30px;
    overflow: hidden;
    background-image: url('../../../assets/image/home/balance_bg.png');
    background-repeat: repeat-x;
    background-position: left;
    background-size: 100%;
  }
  .balance_title {
    position: relative;
    padding-left: 10px;
    border-left: 4px solid #fff;
  }
  .chongzhi_btn {
    width: 203px;
    height: 56px;
    font-size: 18px;
    font-style: normal;
    font-weight: 500;
    line-height: 56rpx;
    color: #6b1ce9;
    text-align: center;
    background: #ffffff;
    border-radius: 28px;
  }
  .custom-table-checkbox {
    [class*='ri'] {
      vertical-align: -2.5px;
      cursor: pointer;
    }

    .el-checkbox {
      margin: 5px 0 5px 8px;
    }
  }
  .horoscope-list {
    padding: 0 10px;
    margin-bottom: 20px;
    border-left: 4px solid #6b1ce9;
    i {
      margin-left: 5px;
      font-size: 18px;
      font-weight: 700;
      color: #409eff;
      cursor: pointer;
    }
  }
  ::v-deep .bgcolor.el-dropdown__popper.el-popper[role='tooltip'] {
    color: #34db74;
    background: #f5fdf8;
    border: 1px solid #34db74;
  }
  .dfjc {
    display: flex;
    justify-content: space-between;
  }
  .dialog-footer {
    display: flex;
    justify-content: space-between;
  }
</style>
<style lang="scss">
  .el-dropdown-menu {
    width: 150px !important;
    padding: 4px !important;
    padding-bottom: 8px !important;
  }
  // 修改位置
  // .el-popper {
  //   position: absolute !important;
  //   left: 550px !important;
  // }
  // 隐藏三角
  .el-popper__arrow {
    display: none;
  }
  // 修改menu-item
  .dropDownStyle .el-dropdown-menu__item {
    padding: 8px 16px !important;
    color: var(---1, #0e1a15);
    font-family: Roboto;
    font-size: 14px;
    font-style: normal;
    font-weight: 400;
    line-height: 22px;
  }
  // 解决hover样式默认
  .dropDownStyle .el-dropdown-menu__item:hover {
    border-radius: 4px !important;
    background: #e6fffd !important;
    color: var(---, #008069) !important;
    font-family: Roboto !important;
    font-size: 14px !important;
    font-style: normal !important;
    font-weight: 400 !important;
    line-height: 22px !important;
  }
  // 解决focus样式默认
  .dropDownStyle .el-dropdown-menu__item:not(.is-disabled):focus {
    border-radius: 4px !important;
    background: #e6fffd !important;
    color: var(---, #008069) !important;
    font-family: Roboto !important;
    font-size: 14px !important;
    font-style: normal !important;
    font-weight: 400 !important;
    line-height: 22px !important;
  }
  // body.vab-theme-blue-white .el-button {
  //   color: #34db74;
  //   background: #f5fdf8;
  //   border: 1px solid #34db74;
  // }
</style>
